package com.linwen.javase.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @ClassName _15ReadWriteLockThread
 * @Description
 * @Author lin
 * @Date 2022/4/23 上午12:44
 * @Version V1.0
 * 读写锁示例
 * 读写锁在读操作上加读锁，写操作上加写锁
 * 写线程之间互斥
 * 写读线程之间互斥
 * 读线程之间共享，不加锁
 */
public class _15ReadWriteLockThread {
    public static void main(String[] args) {
        ReadWriteDeom readWriteDeom = new ReadWriteDeom();
        for (int i = 0; i < 6; i++) {
            final String num = String.valueOf(i);
            new Thread(()->{
                readWriteDeom.add(num,num);
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 6; i++) {
            final String num = String.valueOf(i);
            new Thread(()->{
                readWriteDeom.get(num);
            },String.valueOf(i)).start();
        }
    }
}
class ReadWriteDeom{
    private volatile Map<String,String> map = new HashMap<>();

    private ReentrantReadWriteLock ewLock = new ReentrantReadWriteLock();

    public void add(String key,String val){
        ewLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写之前");
            TimeUnit.SECONDS.sleep(1);
            map.put(key,val);
            System.out.println(Thread.currentThread().getName()+"写之后");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            ewLock.writeLock().unlock();
        }
    }

    public String get(String key){
        ewLock.readLock().lock();
        String result = null;
        try {
            System.out.println(Thread.currentThread().getName()+"读之前");
            result = map.get(key);
            System.out.println(result);
            TimeUnit.SECONDS.sleep(1);
            System.out.println(Thread.currentThread().getName()+"读之后");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            ewLock.readLock().unlock();
        }
        return result;
    }
}